﻿using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MainFrame.Plugs
{
    public class FilterManager
    {
        private static Dictionary<string, IResponseFilter> dataList = new Dictionary<string, IResponseFilter>();

        public static IResponseFilter CreateFilter(string guid)
        {
            lock (dataList)
            {
                var filter = new MyResponseFilter();
                dataList.Add(guid, filter);
                return filter;
            }
        }

        public static IResponseFilter GetFileter(string guid)
        {
            lock (dataList)
            {
                var data = dataList[guid];
                dataList.Remove(guid);
                return data;
            }
        }

    }

    public class MyResourceRequestHandler : ResourceRequestHandler
    {
        protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            return FilterManager.CreateFilter(request.Identifier.ToString()); 
        }

        protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            var requestBody = "";
            var responseBody = "";

            if(request?.PostData?.Elements!=null && request.PostData.Elements.Count > 0)
                requestBody = request.PostData.Elements[0].GetBody(request.GetCharSet());

            var filter = FilterManager.GetFileter(request.Identifier.ToString()) as MyResponseFilter;
            responseBody = Encoding.GetEncoding(response.Charset).GetString(filter.DataAll.ToArray());

            ProxyHelper.HandHttpResponse(request.Url, requestBody, responseBody);
        }
    }
}
